package com.qk.management.web.interceptor;

import com.qk.common.Util.CurrentUserContextHolders;
import com.qk.common.Util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @author: zyx
 * @created: 2025-10-11-14:56
 * @description:
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    private final static String TOKEN_HEADER_NAME = "token";
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (Objects.isNull(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.info("未登录");
            return false;
        }
        //验证token
        try {
            Claims claims = JwtUtil.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("用户是：{}", username);
            Integer id = claims.get("id", Integer.class);
            log.info("用户id是：{}", id);
            CurrentUserContextHolders.set(id);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.info("token验证失败", e);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}
